/**
 * Created by Administrator on 13-12-31.
 */
package main

import (
	// "encoding/json"
	"errors"
	"fmt"
	"math/rand"
	"net"
	"net/rpc"
	"os"
	// "reflect"as
	"runtime"
	"strconv"
	"time"
)

const (
	DeviceNum = 100
	PointNum  = 100
)

var Data string

type Args struct {
	// I, J int
	I int
}

var multResult []byte

type MyMethod int

type Grid struct {
	Lists []PointGroup
}

type PointGroup struct {
	Ciid  string
	Value string
	Aste  int
	Pv    int
	Time  string
}

var rtdata_list Grid

func (this *MyMethod) DataSources(args *Args, reply *string) error {
	if args == nil || reply == nil {
		return errors.New("nil paramters !")
	}
	*reply = "hello world"
	return nil
}

func (this *MyMethod) DataSource(args *Args, reply *[]PointGroup) error {

	if args == nil || reply == nil {
		return errors.New("nil paramters !")
	}
	if args.I > len(rtdata_list.Lists) {
		// bytes, _ := json.Marshal(rtdata_list)
		*reply = rtdata_list.Lists
		return nil
	}
	// fmt.Printf("json:m,%s\n",  stb[0])
	slice := rtdata_list.Lists[:args.I]
	// bytes, _ := json.Marshal(slice)
	*reply = slice
	return nil

}

func (this *MyMethod) init_rtdata() {
	i := 1
	j := 1
	var temp_list []PointGroup
	for i <= DeviceNum {
		for j <= PointNum {
			orderi := PointGroup{Ciid: strconv.Itoa(i) + "." + strconv.Itoa(j), Value: strconv.Itoa(rand.Intn(999)), Pv: rand.Intn(99999), Aste: 0, Time: time.Now().Format("2006-01-02 15:04:05")}
			temp_list = append(temp_list, orderi)
			j = j + 1
		}
		i = i + 1
		j = 1
	}
	rtdata_list.Lists = temp_list
}

func (this *MyMethod) update_rtdata() {
	i := 1
	j := 1
	for i <= DeviceNum {
		for j <= PointNum {
			// rtdata_item := rtdata_list.Lists[i+j-1]
			// fmt.Println(rtdata_list.Lists[(i-1)*DeviceNum+j-1])
			rtdata_list.Lists[(i-1)*DeviceNum+j-1].Time = time.Now().Format("2006-01-02 15:04:05")
			rtdata_list.Lists[(i-1)*DeviceNum+j-1].Value = strconv.Itoa(rand.Intn(999))
			rtdata_list.Lists[(i-1)*DeviceNum+j-1].Aste = rand.Intn(2)
			rtdata_list.Lists[(i-1)*DeviceNum+j-1].Pv = rand.Intn(99999)
			j = j + 1
		}
		i = i + 1
		j = 1
	}
}

func (this *MyMethod) start() {
	this.init_rtdata()
	// fmt.Println(rtdata_list)
	t := time.Tick(1 * time.Second)
	for now := range t {
		this.update_rtdata()
		// fmt.Println(rtdata_list)
		fmt.Println(now)
	}
}

func main() {
	println("start server at" + "7777")
	mm := new(MyMethod)
	runtime.GOMAXPROCS(1) //设置cpu的核的数量，从而实现高并发
	go mm.start()
	server := rpc.NewServer()
	server.Register(mm)
	listener, err := net.Listen("tcp", ":7777")
	defer listener.Close()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error %s\n", err.Error())
		return
	}
	server.Accept(listener)

}
